<template>
    <div class="login-container">
      <el-card class="login-card">
        <h2 class="login-title">实验室成果管理系统</h2>
        <el-form :model="loginForm" ref="loginFormRef" :rules="rules" label-width="80px" hide-required-asterisk>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item class="from-item-login-button">
            <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {useRouter} from 'vue-router'
import http from '@/utils/axios.js'
import { onMounted } from 'vue';

const router = useRouter()

const loginFormRef = ref(null)
const loginForm = ref({
  username: '',
  password: ''
});

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

function checkLogin() {
  if (localStorage.getItem("token") !== null) {
    console.log('login.vue: 已登录，无需登录');
    router.push('/')
  }
}

onMounted(() => {
  checkLogin();
});
const handleLogin = async () => {

  
  // if (loginForm.value.username === "123" && loginForm.value.password === "456") {
  //   ElMessage.success('登录成功');
  //   console.log("账号密码正确")
  //   localStorage.setItem('token', "sjfsfhds");
  //   localStorage.setItem('role', 'ROLE_ADMIN');
  //   router.push('/')
  // } else {
  //   ElMessage.error('账号或密码错误');
  // }

  try {
    const response = await http.post('/auth/login', loginForm.value);
    
    if (response.status === 200)
     {
      const re = response.data;
      if (re['code'] === 2000) {
        localStorage.setItem('token', re['data'][['token']]);
        localStorage.setItem('role', re['data'][['role']]);
        console.log("登陆成功", re['data'][['token']], re['data'][['role']]);
        ElMessage.success('登录成功');

        router.push('/');
      } else {
        ElMessage.error('登录失败');
      }
      
    } else {
      ElMessage.error('登录失败');
      
    }
    
  } catch (error) {
    console.error('错误:', error);
  }
};


</script>
  
  
  <style>


  
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f5f5f5;
  }
  
  .login-card {
    width: 400px;
    padding: 20px;
  }
  
  .login-title {
    text-align: center;
    margin-bottom: 40px;
  }

  .login-button {
    margin-top: 10px;
    margin-left: 70px;
  }
  </style>
  